package algorithm;

/**
 * 二分查找
 */
public class BinarySearch {

    public static void main(String[] args) {

        int[] data1 = { 2,1,3,5,6,4,8,7 };

        int[] data = { 9, -16, 21, 23, -30, -49, 21, 30, 30 };
        int target = 4;

        System.out.println(binarySearch(data1, target));

    }


    public static int binarySearch(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1; // 注意

        while(left <= right) { // 注意
            int mid = (right + left) / 2;
            if(nums[mid] == target)
                return mid;
            else if (nums[mid] < target)
                left = mid + 1; // 注意
            else if (nums[mid] > target)
                right = mid - 1; // 注意
        }
        return -1;
    }
}



